//
//  ImageFliters.metal
//  ImageFilter
//
//  Created by Amos on 2025/10/10.
//

#include <metal_stdlib>
//#include <printf>   //显式包含 printf 支持

using namespace metal;

// 顶点输入结构
struct VertexInput {
    float4 position [[attribute(0)]];
    float2 texCoord [[attribute(1)]];
};

// 顶点输出结构
struct VertexOutput {
    float4 position [[position]];
    float2 texCoord;
};

// 灰度滤镜
kernel void grayscaleFilter(
    texture2d<half, access::read> inputTexture [[texture(0)]],
    texture2d<half, access::write> outputTexture [[texture(1)]],
    uint2 grid [[thread_position_in_grid]]
) {
    half4 color = inputTexture.read(grid);
    half gray = dot(color.rgb, half3(0.299, 0.587, 0.114));
    outputTexture.write(half4(gray, gray, gray, color.a), grid);
}

// 亮度调整滤镜
kernel void brightnessFilter(
    texture2d<half, access::read> inputTexture [[texture(0)]],
    texture2d<half, access::write> outputTexture [[texture(1)]],
    constant float &brightness [[buffer(0)]],
    uint2 grid [[thread_position_in_grid]]
) {
    half4 color = inputTexture.read(grid);
    half4 adjusted = color + half4(half(brightness));
    adjusted.rgb = clamp(adjusted.rgb, 0.0h, 1.0h);
    uint2 tGrid = uint2(inputTexture.get_width() - grid.x, grid.y);
    
//    printf("grid: (%u, %u)\n", grid.x, grid.y);
    
    outputTexture.write(adjusted, tGrid);
}

// 顶点着色器
vertex VertexOutput vertexShader(VertexInput input [[stage_in]]) {
    VertexOutput output;
    output.position = input.position;
    output.texCoord = input.texCoord;
    return output;
}

fragment half4 fragmentShader(VertexOutput input [[stage_in]],
                             texture2d<half> videoTexture [[texture(0)]]) {
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    half4 color = videoTexture.sample(s, input.texCoord);
    return color;
}

